/*
 AMENDMENTS:
 DATE          	NAME        VERSION     DESCRIPTION
--------       	-----       -------     -----------
 30/10/2012    	MKANG       1.0.0       1.Create New.
 */
package com.map.home;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JOptionPane;

import com.map.manager.ConfigManager;
import com.map.manager.DBConnectionManager;
import com.map.manager.MD5Helper;
import com.map.manager.SystemLogManager;
import com.map.util.Constants;

public class SecUsersHome {
	private static SecUsersHome instance = null;

	static final String TABLE_TBLUSER  				= Constants.SCHEMA_ADMIN + "TBLUSER";
	static final String TABLE_TBLACCESSROLE  		= Constants.SCHEMA_ADMIN + "TBLACCESSROLE";
	static final String TABLE_TBLROLEPERMISSION  	= Constants.SCHEMA_ADMIN + "TBLROLEPERMISSION";
	
	/**
	 * Returns the single instance, creating one if it's the first time this
	 * method is called.
	 * 
	 * 
	 * @return IslamicContractHome. The single instance.
	 */
	public static SecUsersHome getInstance() {
		// thread-safe implementation
		if (instance == null) {
			synchronized (SecUsersHome.class) {
				if (instance == null) {
					instance = new SecUsersHome();
				}
			}
		}
		return instance;
	}

	private SecUsersHome() {
		super();
	}

	public boolean login(String organization, String userId,
			String password) throws Exception {
		boolean res = true;
		int TIMEOUT = 10000; // DB connection timeout if unable to get
								// connection in less than 10 seconds
		DBConnectionManager connMgr;

		String connectionPool;
		SystemLogManager sysLogMgr;

		connectionPool = ConfigManager.getInstance().getConnectionPool();
		connMgr = DBConnectionManager.getInstance();
		String timeOutValue = ConfigManager.getInstance().get(
				Constants.DB_WAIT_TIME);
		if (timeOutValue != null) {
			try {
				TIMEOUT = Integer.parseInt(timeOutValue);
			} catch (NumberFormatException e) {
			}
		}
		sysLogMgr = SystemLogManager.getInstance();
		Connection conn = connMgr.getConnection(connectionPool, TIMEOUT);

		PreparedStatement stmt = null;
		ResultSet rs = null;
		String strPwd = "";
		boolean bfound = false;
		try {
			if (conn == null) {
				sysLogMgr.logMsg("login :> Unable To Get Database Connection.");
			} else {
				String strSQL = "";
				strSQL = "SELECT LOGIN_ID,PASSWORD,ROLE_CODE,to_char(last_login_timestamp,'dd/mm/yyyy hh24:mi'),name "
						+ " FROM " + TABLE_TBLUSER +  " WHERE MER_NAME='"
						+ organization
						+ "' AND LOGIN_ID='" + userId + "'";
				System.out.println("myDesk SecUsersHome.java strSQL=" + strSQL);
				stmt = conn.prepareStatement(strSQL);
				rs = stmt.executeQuery();
				String strID = "";
				String strRole = "";

				if (rs.next()) {
					strID = rs.getString(1);
					strPwd = rs.getString(2);
					strRole = rs.getString(3);
					System.out.println("myDesk SecUsersHome.java strPwd="
							+ strPwd);
					System.out
							.println("myDesk SecUsersHome.java MD5Helper.hash(password)="
									+ MD5Helper.hash(password));
					if (strPwd.equals(MD5Helper.hash(password))) {
						bfound = true;
					}
				}
				System.out.println("myDesk SecUsersHome.java LOGONID="
						+ userId);
				stmt.close();
				rs.close();
				stmt = null;
				rs = null;
			} // if (conn == null)

			if (!bfound) {
				res = false;
			}

		} catch (Exception e) {
			res = false;
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "System problem!!! \n\nDetail: "+e.getMessage());
		} catch (Throwable t) {
			res = false;
			t.printStackTrace();
			JOptionPane.showMessageDialog(null, "System problem!!! \n\nDetail: "+t.getMessage());
		} finally {
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e1) {
				}
			}
			connMgr.freeConnection(connectionPool, conn);
		}
		return res;

	}// end of login


	
	public boolean checkPermission(String userId, String moduleCode) throws Exception {
		boolean res = false;
		int TIMEOUT = 10000; // DB connection timeout if unable to get
								// connection in less than 10 seconds
		DBConnectionManager connMgr;
	
		String connectionPool;
		SystemLogManager sysLogMgr;
	
		connectionPool = ConfigManager.getInstance().getConnectionPool();
		connMgr = DBConnectionManager.getInstance();
		String timeOutValue = ConfigManager.getInstance().get(
				Constants.DB_WAIT_TIME);
		if (timeOutValue != null) {
			try {
				TIMEOUT = Integer.parseInt(timeOutValue);
			} catch (NumberFormatException e) {
			}
		}
		sysLogMgr = SystemLogManager.getInstance();
		Connection conn = connMgr.getConnection(connectionPool, TIMEOUT);
	
		PreparedStatement stmt = null;
		ResultSet rs = null;

		try {
			if (conn == null) {
				sysLogMgr.logMsg("check permission :> Unable To Get Database Connection.");
			} else {
				String strSQL = "";
				strSQL = "select a.LOGIN_ID, a.NAME, b.ROLE_CODE, c.MODULE_CODE, c.UPDATE_FLAG, c.WRITE_FLAG "
						+ " from "+ TABLE_TBLUSER +" a, "+ TABLE_TBLACCESSROLE +" b, "+ TABLE_TBLROLEPERMISSION +" c "
						+ " where a.ROLE_CODE = b.ROLE_CODE and b.ROLE_CODE = c.ROLE_CODE "
						+ " and MODULE_CODE = '" + moduleCode + "' and UPDATE_FLAG = '01' and WRITE_FLAG = '01' "
						+ " and LOGIN_ID = '" + userId + "'";
				
				
				System.out.println("myDesk SecUsersHome.java permssion strSQL=" + strSQL);
				stmt = conn.prepareStatement(strSQL);
				rs = stmt.executeQuery();
				String strID 			= "";
				String strName 			= "";
				String strRole 			= "";
				String strModuleCode 	= "";
	
				if (rs.next()) {
					strID 			= rs.getString(1);
					strName 		= rs.getString(2);
					strRole 		= rs.getString(3);
					strModuleCode 	= rs.getString(4);

					System.out.println("myDesk SecUsersHome.java strModuleCode=" + strModuleCode);
					
					res = true;
				}
				System.out.println("myDesk SecUsersHome.java LOGONID="
						+ userId);
				stmt.close();
				rs.close();
				stmt = null;
				rs = null;
			} // if (conn == null)
	
		} catch (Exception e) {
			res = false;
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "System problem!!! \n\nDetail: "+e.getMessage());
		} catch (Throwable t) {
			res = false;
			t.printStackTrace();
			JOptionPane.showMessageDialog(null, "System problem!!! \n\nDetail: "+t.getMessage());
		} finally {
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e1) {
				}
			}
			connMgr.freeConnection(connectionPool, conn);
		}
		return res;
	
	}// end of permission

}// end class